package com.ccp.dev.system.util;

import com.ccp.dev.core.basic.util.ContextUtil;
import com.ccp.dev.core.util.AppUtil;
import com.ccp.dev.core.util.BeanUtils;
import com.ccp.dev.core.util.StringUtil;
import com.ccp.dev.system.configuration.CustomPwdEncoder;
import com.ccp.dev.system.model.*;
import com.ccp.dev.system.service.ResourcesService;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * security 工具类
 * @author y
 */
public class SecurityUtil {

	/**
	 * 登录系统让系统实现登录。
	 * @param request
	 * @param userId		用户Id
	 * @param pwd			密码
	 * @param isIgnorePwd	是否忽略密码
	 * @return 
	 */
	public static Authentication login(HttpServletRequest request, String userId, String pwd, boolean isIgnorePwd){
		AuthenticationManager authenticationManager =(AuthenticationManager) AppUtil.getBean("authenticationManager");
		CustomPwdEncoder.setIngore(isIgnorePwd);
		UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(userId, pwd);
		authRequest.setDetails(new WebAuthenticationDetails(request));
		SecurityContext securityContext = SecurityContextHolder.getContext();
		Authentication auth = authenticationManager.authenticate(authRequest);
		securityContext.setAuthentication(auth);
		return auth;
	}

	/**
	 * 根据系统和功能别名判断是否有权限访问。
	 * @param systemId 系统id
	 * @param roleId 角色id
	 * @param function 功能别名
	 * @return
	 */
	public static boolean hasFuncPermission(String systemId,String roleId, String function){
		if(StringUtil.isEmpty(systemId)||StringUtil.isEmpty(roleId)||StringUtil.isEmpty(function)){
			return false;
		}
		//是否是超管登录
		if(ContextUtil.isSuperAdmin()){
			return true;
		}
		ResourcesService resourcesService=(ResourcesService)AppUtil.getBean(ResourcesService.class);
		ResourcesUrlExt resourcesUrlExt = resourcesService.getFunctionBySystemIdAndRoleId(systemId,roleId,function);
		if(BeanUtils.isNotEmpty(resourcesUrlExt)){
			return true;
		}else{
			return false;
		}
	}
}



 
